﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using SP = Microsoft.SharePoint.Client;

//Desarrollado por Roberto Marcos (info@robertomarcos.com)
//http://sharepointworks.blogspot.com

namespace FolderToSharepointCopier
{
    public partial class FolderCopy : ServiceBase
    {
        public Uri UrlDocumentLibrarySharepoint { get; set; }

        public FolderCopy()
        {
            InitializeComponent();

            //CREAMOS EL LOG
            if (!System.Diagnostics.EventLog.SourceExists("FolderToSharepoint"))
            {
                System.Diagnostics.EventLog.CreateEventSource(
                    "FolderToSharepoint", "FolderToSharepointLog");
            }
            evtLog.Source = "FolderToSharepoint";
            evtLog.Log = "FolderToSharepointLog";
        }

        protected override void OnStart(string[] args)
        {
            evtLog.WriteEntry("FolderToSharepoint service Start");
            //Se reciben  2 parametros la carpeta a mirar y la url completa de la libreria de documentos sharepoint donde se copia el fichero.
            //Debugger.Launch();

            string directorypath = ConfigurationSettings.AppSettings["RutaCopiado"];
            if (!string.IsNullOrEmpty(directorypath))
            {
                fsWatcher.Path = directorypath;
                evtLog.WriteEntry(string.Format("Observando la carpeta {0} ", directorypath));
            }
            else
            {
                evtLog.WriteEntry(string.Format("La carpeta {0} no existe", directorypath));
            }
            string rutasharepoint = ConfigurationSettings.AppSettings["RutaSharepoint"];

            if (rutasharepoint.Contains("http://"))
            {
                UrlDocumentLibrarySharepoint = new Uri(rutasharepoint);
                evtLog.WriteEntry(string.Format("Lo ficheros se copiaran a la document library ubicada en {0} ", rutasharepoint));
            }
            else
            {
                evtLog.WriteEntry(string.Format("La ruta {0} no existe", rutasharepoint));
            }
        }

        protected override void OnStop()
        {
            evtLog.WriteEntry("FolderToSharepoint service Stop");
        }

        private void evtLog_EntryWritten(object sender, EntryWrittenEventArgs e)
        {
        }

        protected override void OnPause()
        {
            base.OnPause();
            evtLog.WriteEntry("FolderToSharepoint service Paused");
        }

        protected override void OnContinue()
        {
            base.OnContinue();
            evtLog.WriteEntry("FolderToSharepoint service Continue");
        }

        private void fsWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
        {
            switch (e.ChangeType)
            {
                case System.IO.WatcherChangeTypes.Changed:
                    evtLog.WriteEntry("Nuevo fichero cambiado " + e.FullPath);
                    CopiaArchivoSp2010(e.FullPath);
                    break;
                case System.IO.WatcherChangeTypes.Created:
                    evtLog.WriteEntry("Nuevo Fichero creado " + e.FullPath);
                    CopiaArchivoSp2010(e.FullPath);
                    break;
                case System.IO.WatcherChangeTypes.Deleted:
                    break;
                case System.IO.WatcherChangeTypes.Renamed:
                    evtLog.WriteEntry("Fichero renombrado " + e.FullPath);
                    CopiaArchivoSp2010(e.FullPath);
                    break;
            }
        }

        //private void CopiaArchivo(string ruta) {
        //    try
        //    {
        //        using (SPSite objSite = new SPSite("http://"+UrlDocumentLibrarySharepoint.Host))
        //        {
        //            using (SPWeb objWeb = objSite.OpenWeb())
        //            {
        //                SPFolder mylibrary = objWeb.Folders[UrlDocumentLibrarySharepoint.PathAndQuery];

        //                string filename = System.IO.Path.GetFileName(ruta);
        //                byte[] fileBytes = System.IO.File.ReadAllBytes(ruta);
        //                string destUrl = UrlDocumentLibrarySharepoint + "/" + filename;

        //                // Ponemos AllowUnsafeUpdates = true para evitar errores
        //                objWeb.AllowUnsafeUpdates = true;

        //                SPFile destFile = mylibrary.Files.Add(System.IO.Path.GetFileName(destUrl), fileBytes, true);

        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        evtLog.WriteEntry(string.Format("Error: {0} /n Excepcion:{1}/n Source:{2}" ,ex.Message,ex.InnerException,ex.Source));
        //    }

        //}
        private void CopiaArchivoSp2010(string ruta)
        {
            try
            {
                using (SP.ClientContext context = new SP.ClientContext("http://" + UrlDocumentLibrarySharepoint.Host))
                {
                    //Obtengo la coleccion de folders de la raiz del sitio
                    SP.FolderCollection folders = context.Web.Folders;
                    context.Load(folders);
                    context.ExecuteQuery();

                    //Obtengo una instancia de la DL como objeto Folder
                    var fc = from folder in folders.ToList()
                             where (folder.Name == UrlDocumentLibrarySharepoint.PathAndQuery.Replace("/", ""))
                             select folder;
                    SP.Folder documentsFolder = (SP.Folder)fc.FirstOrDefault();

                    //creo el arreglo de bytes con el contenido del archivo
                    string filename = System.IO.Path.GetFileName(ruta);
                    var fStream = File.OpenRead(ruta);
                    byte[] content = new byte[fStream.Length];
                    fStream.Read(content, 0, (int)fStream.Length);
                    fStream.Close();

                    // Lo cargo en un objeto FileCreationInformation
                    SP.FileCreationInformation fileInfo = new SP.FileCreationInformation();
                    fileInfo.Content = content;
                    fileInfo.Overwrite = true;
                    fileInfo.Url = filename;

                    // Y lo subo
                    documentsFolder.Files.Add(fileInfo);
                    context.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
                evtLog.WriteEntry(string.Format("Error: {0} /n Excepcion:{1}/n Source:{2}", ex.Message, ex.InnerException, ex.Source));
            }
        }
    }
}